package model

import (
	"fmt"
	"gorm.io/gorm"
	"member-srv/basic/config"
	"time"
)

type Video struct {
	Id             uint32         `gorm:"column:id;type:int UNSIGNED;primaryKey;not null;" json:"id"`
	Title          string         `gorm:"column:title;type:varchar(60);comment:标题;not null;" json:"title"`                                           // 标题
	Tag            string         `gorm:"column:tag;type:varchar(30);comment:分区标签;not null;" json:"tag"`                                             // 分区标签
	ImageUrl       string         `gorm:"column:image_url;type:varchar(300);comment:封面URL;not null;" json:"image_url"`                               // 封面URL
	Info           string         `gorm:"column:info;type:varchar(60);comment:简介;not null;" json:"info"`                                             // 简介
	Status         int8           `gorm:"column:status;type:tinyint(1);comment:版权类型: 0:免费 1:会员专享;not null;default:0;" json:"status"`                 // 版权类型: 0:免费 1:会员专享
	VideoUrl       string         `gorm:"column:video_url;type:varchar(300);comment:视频URL;not null;" json:"video_url"`                               // 视频URL
	ProtobufStatus int8           `gorm:"column:protobuf_status;type:tinyint(1);comment:审核状态: 0-审核中 1-审核通过 2-审核失败;not null;" json:"protobuf_status"` // 审核状态: 0-审核中 1-审核通过 2-审核失败
	CreatedAt      time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt      time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt      gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (r *Video) TableName() string {
	return "video"
}

func (v *Video) AddVideo() error {
	return config.DB.Create(&v).Error
}

func (v *Video) GetPageVideo(page, pageSize int) (list []*Video, err error) {
	err = config.DB.Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 排序
func (v *Video) GetOrderVideo(key string, page, pageSize int) (list []*Video, err error) {
	err = config.DB.
		Order(fmt.Sprintf("%d desc", key)).Scopes(Paginate(page, pageSize)).
		Find(&list).Error
	return
}

//筛选

func (v *Video) GetKeyVideo(key string, page, pageSize int) (list []*Video, err error) {
	err = config.DB.
		Where("tag or status or title", key, key, key).
		Scopes(Paginate(page, pageSize)).
		Find(&list).Error
	return
}
